package com.css.apps.task.admin.action;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.css.apps.base.log.model.LogConstant;
import com.css.apps.base.log.model.LogPart;
import com.css.apps.task.exec.DoJob;
import com.css.apps.task.model.TTask;
import com.css.core.configuration.Environment;
import com.css.db.query.QueryCache;
import com.css.db.query.TransactionCache;
import com.css.util.Ajax;
import com.css.util.Json;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.css.webbase.webwork.action.AdminAction;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ModelDriven;

@SuppressWarnings("serial")
public class AddTimerTask extends AdminAction implements ModelDriven {

	private static Log log = LogFactory.getLog(AddTimerTask.class);
	private TTask item;

	public Object getModel() {
		return item;
	}

	public AddTimerTask() {
		item = new TTask();
	}

	public String adminGo() {
		LogPart lp = new LogPart();
		lp.setOpObjType(TTask.class.getName());
		lp.setOpType(LogConstant.LOG_TYPE_ADD);
		lp.setRelObjId("");
		lp.setRelObjType("");
		lp.setLogData(Json.object2json(item));
		lp.setLogLevel(LogConstant.LOG_LEVEL_COMMON);
		TransactionCache tx = null;
		try {
			if (StringHelper.isEmpty(item.getName()) || StringHelper.isEmpty(item.getExeClass())
					|| StringHelper.isEmpty(item.getExeCorn()) || StringHelper.isEmpty(item.getOpenFlag())
					|| StringHelper.isEmpty(item.getJobType())) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.fieldEmpty"));
				return Action.ERROR;
			}
			if ("2".equals(item.getJobType()) && StringHelper.isEmpty(item.getExePara())) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.fieldEmpty"));
				return Action.ERROR;
			}
			Object uuid = new QueryCache("select a.uuid from TTask a where a.name=:name ")
					.setParameter("name", item.getName()).setMaxResults(1).uniqueResult();
			if (uuid != null) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("sysmgrMsg.nameExist"));
				return Action.ERROR;
			}
			tx = new TransactionCache();
			tx.save(item);
			tx.commit();
			new DoJob().addTask(item);
			result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS, Messages.getString("systemMsg.success"),
					item.getUuid());
			lp.setResult(LogConstant.RESULT_SUCCESS);
			lp.setOpObjId(item.getUuid());
			return Action.SUCCESS;

		} catch (Exception ex) {
			lp.setOpObjId(item.getUuid());
			lp.setResult(LogConstant.RESULT_ERROR);
			if (tx != null)
				tx.rollback();
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.dbFaild"));
			log.error(ex.getMessage(), ex);
			return Action.ERROR;
		}
	}

	public TTask getItem() {
		return item;
	}

	public void setItem(TTask item) {
		this.item = item;
	}

}